// ==UserScript==
// @name         b站我的订阅页面交互优化
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  主要优化细节：按左右方向键AD键可翻页；显示开播时间；显示播放量、弹幕、系列追番数；显示评分及评分人数；鼠标悬浮至标题可显示完整标题名字；翻页时将页面自动滚动至合适高度；调整分页栏高度，使之刚好在一屏内展示
// @author       移影残风
// @match        https://space.bilibili.com/*/bangumi
// @grant        none
// @require      https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js
// ==/UserScript==

(function() {
  'use strict'
  window.onload = function() {
    const filterContentDom = document.getElementsByClassName('filter-content')[0]
    if (filterContentDom) {
      filterContentDom.style.marginTop = '190px'
      filterContentDom.style.marginRight = '-120px'
      document.getElementsByClassName('be-dropdown-item').forEach(item => {
        if (item.innerText === '在看') {
          item.click()
        }
      })
    }
    window.scrollTo({
      top: document.getElementById('page-bangumi').offsetTop,
      behavior: 'smooth'
    })
    document.getElementsByClassName('bangumi-pagelistbox clearfix')[0].style.bottom = '30px'
    document.getElementsByClassName('bangumi-pagelistbox clearfix')[0].style.position = 'relative'
    const userId = location.href.match(/https:\/\/space.bilibili.com\/(.*)\/bangumi/)[1]
    const currentPage = document.getElementsByClassName('p active')[0].innerText
    const curFilterDom = document.getElementsByClassName('cur-filter')[0]
    if (curFilterDom) {
      curFilterDom.addEventListener('DOMCharacterDataModified', function(e) {
        setTimeout(function() {
          window.scrollTo({
            top: document.getElementById('page-bangumi').offsetTop,
            behavior: 'smooth'
          })
          document.getElementsByClassName('bangumi-pagelistbox clearfix')[0].style.bottom = '30px'
          document.getElementsByClassName('bangumi-pagelistbox clearfix')[0].style.position = 'relative'
        }, 200)
        const followStatus = getFollowStatus(e.newValue)
        getDataAndRender(followStatus, currentPage, userId)
      })
    } else {
      getDataAndRender(0, currentPage, userId)
    }

    $('.p').click(function(e) {
      const curFilterDom = document.getElementsByClassName('cur-filter')[0]
      let followStatus = 0
      if (curFilterDom) {
        const curFilterText = curFilterDom.innerText
        followStatus = getFollowStatus(curFilterText)
      }
      const currentPage = e.target.innerText
      getDataAndRender(followStatus, currentPage, userId)
      setTimeout(function() {
        window.scrollTo({
          top: document.getElementById('page-bangumi').offsetTop,
          behavior: 'smooth'
        })
        document.getElementsByClassName('bangumi-pagelistbox clearfix')[0].style.bottom = '30px'
        document.getElementsByClassName('bangumi-pagelistbox clearfix')[0].style.position = 'relative'
      }, 200)
    })

    window.addEventListener('keydown', function(e) {
      switch (e.keyCode) {
        case 65:
          smoothToCenter(0)
          break
        case 68:
          smoothToCenter(1)
          break
        case 37:
          smoothToCenter(0)
          break
        case 39:
          smoothToCenter(1)
          break
        default:
          break
      }
    })
  }

  function getDataAndRender(followStatus, currentPage, userId) {
    const url = `https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=${followStatus}&pn=${currentPage}&ps=15&vmid=${userId}`
    setTimeout(function() {
      $.get(url, function(data) {
        const list = data.data.list
        $('.pgc-item-title').each(function(index, item) {
          const title = item.innerText
          $(item).parent().attr('title', title)
          const matchedItem = list.filter(value => {
            return value.title.replace(/ /g, '') === title.replace(/ /g, '')
          })[0]
          let score = ''
          let count = ''
          const releaseDateShow = matchedItem.publish.release_date_show
          let view = matchedItem.stat.view
          let danmaku = matchedItem.stat.danmaku
          let seriesFollow = matchedItem.stat.series_follow
          view = (parseFloat(view) / 10000).toFixed(1)
          danmaku = (parseFloat(danmaku) / 10000).toFixed(1)
          seriesFollow = (parseFloat(seriesFollow) / 10000).toFixed(1)
          if (matchedItem.rating && matchedItem.rating.score) {
            score = matchedItem.rating.score
            count = matchedItem.rating.count
          }
          $(item).next().css('margin-top', '-8px')
          $(item).next().next().css('margin-top', '-5px')
          $(item).next().next().next().css('margin-top', '-5px')
          $(item).next().next().append(`<span> | ${releaseDateShow}开播</span>`)
          $(item).parent().append(`<div style="margin-top: -6px;color: #999999">${view}万播放 ${danmaku}万弹幕 ${seriesFollow}万系列追番</div>`)
          $(item).parent().append(`<div style="color: #ffa726;"><span style="font-size: 20px">${score}</span>${score === '' ? '' : '分'}<span> ${count}</span>${count === '' ? '' : '人评分'}</div>`)
        })
      })
    }, 200)
  }

  function smoothToCenter(leftOrRight) {
    if (leftOrRight === 0) {
      document.getElementsByClassName('p active')[0].previousElementSibling.click()
    } else if (leftOrRight === 1) {
      document.getElementsByClassName('p active')[0].nextElementSibling.click()
    }
    setTimeout(function() {
      window.scrollTo({
        top: document.getElementById('page-bangumi').offsetTop,
        behavior: 'smooth'
      })
      document.getElementsByClassName('bangumi-pagelistbox clearfix')[0].style.bottom = '30px'
      document.getElementsByClassName('bangumi-pagelistbox clearfix')[0].style.position = 'relative'
    }, 200)
  }

  function getFollowStatus(text) {
    let status = 0
    switch (text) {
      case '全部':
        status = 0
        break
      case '想看':
        status = 1
        break
      case '在看':
        status = 2
        break
      case '看过':
        status = 3
        break
    }
    return status
  }
})()
